package com.example.community.userHome;

import com.example.community.dao.*;
import com.example.community.model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/userCenterServlet")
public class UserCenterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer currentUserUsNo = (Integer) req.getSession().getAttribute("currentUserUsNo");
        UsersDao usersDao = new UsersDao();
        Users users = usersDao.fandById(currentUserUsNo);
        String usAddress = getUsAddress(currentUserUsNo);
        req.setAttribute("users",users);
        req.setAttribute("usAddress",usAddress);
        req.getRequestDispatcher("/WEB-INF/userHome/userCenter.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    private String getUsAddress(Integer usNo){
        RoomDao roomDao = new RoomDao();
        Room room = roomDao.fandByUsNo(usNo);
        Integer rNo = null;
        try {
            rNo = room.getrNo();
        }catch (Exception e){
            rNo = null;
        }finally {
            if (rNo != null){
                Integer unNo = room.getUnNo();
                UnitDao unitDao = new UnitDao();
                Unit unit = unitDao.fandById(unNo);
                Integer fNo = unit.getfNo();
                FloorDao floorDao = new FloorDao();
                Floor floor = floorDao.fandById(fNo);
                Integer ctNo = floor.getCtNo();
                ComtyDao comtyDao = new ComtyDao();
                Comty comty = comtyDao.fandById(ctNo);
                String address = "" + comty.getCtName() + floor.getfName() + unit.getUnName() + room.getrId();
                return address;
            }else return null;
        }
    }
}
